package com.reggie.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.reggie.constant.MessageConstant;
import com.reggie.constant.StatusConstant;
import com.reggie.dto.DishDTO;
import com.reggie.dto.DishPageQueryDTO;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.exception.DeletionNotAllowedException;
import com.reggie.mapper.DishFlavorMapper;
import com.reggie.mapper.DishMapper;
import com.reggie.mapper.SetmealDishMapper;
import com.reggie.mapper.SetmealMapper;
import com.reggie.result.PageResult;
import com.reggie.result.R;
import com.reggie.service.DishService;
import com.reggie.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;




    /**
     * 添加菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        //将前端提交的表单数据 拷贝到Dish对象中
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
        //获取菜品的主键值  将需要保存的口味提交到口味表
        Long id = dish.getId();

        //获取菜品关联的口味
        List<DishFlavor> flavors = dishDTO.getFlavors();

        //判断这个菜品是否有口味选项
        if(flavors!=null||flavors.size()>0){
            //如果菜品中不为空 执行添加口味
            flavors.forEach(item->{
                //将获取到的菜品 口味遍历添加到DishDTO
                item.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    //分页查询
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //利用分页工具传入分页大小 当前页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //调用Mapper将查询到的结果封装到page集合
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        //这里如果不创建对应的Mapper 传入 getResult不会有提示
        return new PageResult(page.getTotal(),page.getResult());

    }

    //批量删除
    @Transactional
    public void deleteBatch(List<Long> ids) {

        ids.forEach(id->{
            Dish dish = dishMapper.getById(id);
            //判断当前要删除的菜品状态是否为起售中
            if(dish.getStatus() == StatusConstant.ENABLE){
                //如果是起售中，抛出业务异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //判断当前要删除的菜品是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds != null && setmealIds.size() > 0){
            //如果关联了，抛出业务异常
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的数据
        ids.forEach(id -> {
            dishMapper.deleteById(id);
            //删除口味表中的数据
            dishFlavorMapper.deleteByDishId(id);
        });
    }

    //根据id查询菜品和关联的口味
    public DishVO getByIdWithFlavor(Long id) {
        return dishMapper.getByIdWithFlavor(id);
    }

    //修改菜品
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //修改菜品表dish，执行update操作
        dishMapper.update(dish);

        //删除当前菜品关联的口味数据，操作dish_flavor，执行delete操作
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //插入最新的口味数据，操作dish_flavor，执行insert操作
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    //菜品的起售禁售
    @Transactional
    public void startOrStop(Integer status, Long id) {
        // update dish set status = ? where id = ?
        dishMapper.updateStatusById(status,id);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                Map mapSetmeal = new HashMap();
                mapSetmeal.put("status", StatusConstant.DISABLE);
                mapSetmeal.put("ids", setmealIds);
                setmealMapper.updateStatusByIds(mapSetmeal);
            }
        }
    }

    //根据分类id查询菜品
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }


    //查询菜品和口味
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<DishVO> list = dishMapper.listWithFlavor(dish);
        return list;
    }


}



